package com.tgy.programmer_code_interview_guide._03_binarytree;

import com.tgy.common.printer.BinaryTreeInfo;
import com.tgy.common.printer.BinaryTrees;
import com.tgy.leetcode.TreeNode;

public class _16_通过有序数组生成平衡搜索二叉树 {

    public static TreeNode generalBSTreeByArr(int [] nums) {

        if (nums == null || nums.length  == 0) {

            return null;
        }

        return doGeneralBSTreeByArr(nums, 0, nums.length - 1);
    }

    public static TreeNode doGeneralBSTreeByArr(int[] nums, int left, int right) {

        if (left > right) {

            return null;
        }

        // 1 2 3 4 5 6
        int mid = left + ((right - left) >> 1);

        TreeNode root = new TreeNode(nums[mid]);

        root.left = doGeneralBSTreeByArr(nums,left,mid - 1);
        root.right = doGeneralBSTreeByArr(nums,mid + 1,right);

        return root;
    }

    public static void main(String[] args) {

        int[] nums = {1,2,3,4,5,6,7,8,9,10,11,12};
        TreeNode treeNode = generalBSTreeByArr(nums);

        BinaryTrees.print(new BinaryTreeInfo() {
            @Override
            public Object root() {
                return treeNode;
            }

            @Override
            public Object left(Object node) {
                return ((TreeNode)node).left;
            }

            @Override
            public Object right(Object node) {
                return ((TreeNode)node).right;
            }

            @Override
            public Object string(Object node) {
                return ((TreeNode)node).val;
            }
        });

    }
}
